package com.absorbx.jcrapp.dao.Jcr;

import java.io.IOException;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springmodules.jcr.JcrCallback;
import org.springmodules.jcr.JcrConstants;
import org.springmodules.jcr.JcrTemplate;
import org.springmodules.jcr.support.JcrDaoSupport;

import com.absorbx.jcrapp.dao.AdDao;
import com.absorbx.jcrapp.model.Ad;

public class AdDaoJcr implements AdDao {
	final Logger logger = LoggerFactory.getLogger(JcrDaoSupport.class);
	@Autowired
	protected JcrTemplate template = null;

	@Override
	public Ad getAd() {
		logger.debug("begin to fetch ad");

		final Ad ad = new Ad();

		template.execute(new JcrCallback() {
			public Object doInJcr(Session session) throws RepositoryException,
					IOException {
				Node root = session.getRootNode();

				Node adNode = root.getNode("ad");
				adNode.getName();

				ad.setHeadLine(adNode.getProperty("headLine").getString());
				logger.debug("done the saving");

				return null;
			}
		});
		return ad;
	}

	@Override
	public List<Ad> getAds() {
		return null;
	}

	public void saveAd(final Ad ad) {
		logger.debug("begin to save add" + ad.getHeadLine());

		template.execute(new JcrCallback() {
			public Object doInJcr(Session session) throws RepositoryException,
					IOException {
				Node root = session.getRootNode();
				JcrConstants jcrConstants = new JcrConstants(session);

				Node adNode = root.addNode("ad");
				adNode.setProperty("headLine", ad.getHeadLine());

				session.save();
				logger.debug("done the saving");

				return null;
			}
		});

	}

	/**
	 * Gets JCR template.
	 */
	public JcrTemplate getTemplate() {
		return template;
	}

	/**
	 * Sets JCR template.
	 */
	public void setTemplate(JcrTemplate template) {
		this.template = template;
	}
}
